//
//  JDPaddingLabel.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/22.
//

import UIKit

class JDPaddingLabel: UILabel {

    var edgeInsets: UIEdgeInsets?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.edgeInsets = UIEdgeInsets.init(top: 9, left: 16, bottom: 9, right: 16)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.edgeInsets = UIEdgeInsets.init(top: 9, left: 16, bottom: 9, right: 16)
    }
    
    // 修改绘制文字的区域，edgeInsets增加bounds
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        /*
         调用父类该方法
         注意传入的UIEdgesInsetsInsetRect(bounds,self.edgesInsets),bounds是真正的绘制区域
         */
        var rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        // 根据edgeInsets，修改绘制文字的bounds
        rect.origin.x -= (self.edgeInsets?.left ?? 0)
        rect.origin.y -= (self.edgeInsets?.top ?? 0)
        rect.size.width += (self.edgeInsets?.left ?? 0) + (self.edgeInsets?.right ?? 0)
        rect.size.height += (self.edgeInsets?.top ?? 0) + (self.edgeInsets?.bottom ?? 0)
        return rect
    }
    
    // 绘制文字
    override func drawText(in rect: CGRect) {
        // 令绘制区域为原始区域，增加的内边距区域不绘制
        super.drawText(in: rect.inset(by: self.edgeInsets ?? .zero))
    }

}
